package com.lingdian.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class HttpUtil {


/**
* GET璇锋眰 榛樿鏄� utf-8 缂栫爜
* @param url
* @param params
* @return
*/
public static String get(String url, String params){
return get(url, params, Charset.forName("utf-8"));
}

/**
* GET璇锋眰
* @param url 璇锋眰URL
* @return 
*/
public static String get(String url, String params, Charset charset) {
String result = "";
InputStream in = null;
if (null != params && !params.equals("")) {
if (url.contains("?")) {// 鍖呭惈?,鍚庨潰鍔�&鐩存帴濉姞
url += "&" + params;
} else {
url += "?" + params;
}
}

try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.connect();
in = conn.getInputStream();
result = readInputStream(charset, in);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
return result;
}


/**
* POST璇锋眰 榛樿鏄� utf-8 缂栫爜
* @param url
* @param params
* @return
*/
public static String post(String url, String params){
return post(url, params, Charset.forName("utf-8"));
}

/**
*POST璇锋眰
* @param url 璇锋眰URL
* @param param 璇锋眰鍙傛暟锛岃姹傚弬鏁版牸寮� name1=value1&name2=value2
* @return 
*/
public static String post(String url, String param, Charset charset) {
PrintWriter out = null;
InputStream in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 璁剧疆閫氱敤鐨勮姹傚睘鎬�
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 鍙戦€丳OST璇锋眰蹇呴』璁剧疆濡備笅涓よ
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();


in = conn.getInputStream();
result = readInputStream(charset, in);


} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
} catch (Exception ex) {
}
}
return result;
}

private static String readInputStream(Charset charset, InputStream in)
throws IOException {
byte[] bytes = new byte[1024];
int length = -1;
ByteArrayOutputStream byteOutput= new ByteArrayOutputStream();
while ((length = in.read(bytes)) != -1) {
byteOutput.write(bytes, 0, length);
}
return new String(byteOutput.toByteArray(), charset);
}
}
